const http = require('http')
const path = require('path')
const fs = require('fs')
const mime = require('mime')
const zlib = require('zlib')

const server = http.createServer(async (req, res) => {
    let filePath = path.resolve(__dirname, path.join('www', req.url))
    if (fs.existsSync(filePath)) {
        const stat = fs.statSync(filePath)
        if (stat.isDirectory()) {
            filePath = path.join(filePath, 'index.html')
        }
        if (fs.existsSync(filePath)) {
            const { ext } = path.parse(filePath)
            const stat = fs.statSync(filePath)
            const timeStamp = req.headers['if-modified-since']//浏览器缓存的上一次修改的时间
            let status = 200
            if (timeStamp && Number(timeStamp) === stat.mtimeMs) {
                status = 304
            }
            const mimeType = mime.getType(ext)
            const responseHeaders = {
                'Content-Type': mimeType,
                'Cache-Control': 'max-age=86400',
                'last-modified': stat.mtimeMs,
            }
            const acceptEncoding = req.headers['accept-encoding']//客户端支持的压缩方式
            const compress = /^(text|application)\//.test(mimeType)
            if (compress) {
                acceptEncoding.split(/\s*,\s*/).some(encoding => {
                    if (encoding === 'gzip') {
                        responseHeaders['Content-Encoding'] = 'gzip'
                        return true
                    }
                    if (encoding === 'deflate') {
                        responseHeaders['Content-Encoding'] = 'deflate'
                        return true
                    }
                    if (encoding === 'br') {
                        responseHeaders['Content-Encoding'] = 'br'
                        return true
                    }
                    return false
                })
            }
            res.writeHead(status, responseHeaders)
            const compressionEncoding = responseHeaders['Content-Encoding']

            if (status === 200) {
                const fileStream = fs.createReadStream(filePath)
                if (compress && compressionEncoding) {
                    let comp=null
                    if(compressionEncoding === 'gzip'){
                        comp=zlib.createGzip()
                    }
                    else if(compressionEncoding === 'deflate'){
                        comp=zlib.createDeflate()
                    }
                    else if(compressionEncoding === 'br'){
                        comp=zlib.createBrotliCompress()
                    }
                    fileStream.pipe(comp).pipe(res)
                } else {
                    fileStream.pipe(res)

                }
            } else {
                res.end()
            }

        }


    }

})
server.listen(3000, () => {
    console.log('server is running at http://localhost:3000')
})



